import jwt from "jsonwebtoken";
const secret = "taoshuai";
const cookieKey = "Token";

// 发放jwt
export const publishJwt = (res: any, info: Object, maxAge: number = 3600 * 24): string => {
    const token = jwt.sign(info, secret, {
        expiresIn: maxAge,
    });
    // 添加到cookie
    res.cookie(cookieKey, token, {
        maxAge: maxAge,
        path: "/",
    });
    // res.header("Access-Control-Expose-Headers", "Authorization")
    res.header("Authorization", "Bearer " + token);
    return token;
};

// 验证jwt
export const verifyJwt = (token: string) => {
    return new Promise((resolve, reject) => {
        try {
            resolve( jwt.verify(token.replace("Bearer ", ""), secret) )
        } catch (error) {
            reject( "请重新登录" )
        }
    });
};
